package my.mybatis.common.util;

import my.mybatis.common.exception.BaseException;
import my.mybatis.common.exception.ErrorCode;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author:wangbin.
 * @Description.
 * @Date:Created in 16:33 2017/9/19.
 * @Modified By:
 */
public class CheckData {
    /**
     * 数据校验
     * @param bindingResult
     * @return
     */
    public static List<String> checkData(BindingResult bindingResult)
    {
        if(bindingResult.hasErrors())
        {
            //输出错误信息
            List<ObjectError> allerrors=bindingResult.getAllErrors();
            List<String> errorList = new ArrayList<String>();
            for(ObjectError error: allerrors)
                errorList.add(error.getDefaultMessage());
            return errorList;
        }
        return null;
    }

    /**
     * bean数据校验，抛出异常
     * @param bindingResult
     * @throws BaseException
     */
    public static void checkDateThrowException(BindingResult bindingResult) throws BaseException
    {
        if(bindingResult.hasErrors())
        {
            //输出错误信息
            List<ObjectError> allerrors=bindingResult.getAllErrors();
            List<String> errorList = new ArrayList<String>();
            for(ObjectError error: allerrors)
                errorList.add(error.getDefaultMessage());
            throw new BaseException(ErrorCode.DATA_CHECK_ERROR.getCode(),errorList);
        }
    }
}
